/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisyimport.foxml;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class Pages {

    private static final Logger logger = Logger.getLogger(Pages.class.getName());
    private final Map<Page, Page> predecessorSucessorMap = new HashMap<Page, Page>();
    private final Map<String, Page> idPageMap = new HashMap<String, Page>();
    private Page firstPage = null;

    Pages(List<Page> pageList) {
        Page predecessor = null; //predecessor for first is null
        for (Page page : pageList) {
            addPage(predecessor, page);
            predecessor = page;
        }
    }

    private void addPage(Page predecessor, Page page) {
        addToLinkedPages(predecessor, page);
        addToLabelPageMap(page);
//        if (page.getPageNumber() != null) {
//            addToNumberPageMap(page);
//        }
    }

    private void addToLinkedPages(Page predecessor, Page page) {
        if (predecessor == null) { //null:firstPage presented
            firstPage = page;
        } else {
            predecessorSucessorMap.put(predecessor, page);
        }
    }

    private void addToLabelPageMap(Page page) {
        String id = page.getId();
        Page pagePresent = idPageMap.get(id);
        if (pagePresent == null) {
            idPageMap.put(id, page);
        } else {
            logger.log(Level.SEVERE, "uuid for page with id {0} already present! Found ''{1}'', wanted to add ''{2}''", new Object[]{page.getLabel(), pagePresent.getUuid(), page.getUuid()});
        }
    }

    public Page getPageById(String id) {
        return idPageMap.get(id);
    }

    public Page nextPage(Page page) {
        return predecessorSucessorMap.get(page);
    }

    public void printPageList() {
        Page page = firstPage;
        int counter = 0;
        while (true) {
            System.out.println(counter++ + ":" + page.getId() + "," + page.getLabel());
            page = predecessorSucessorMap.get(page);
            if (page == null) {
                break;
            }
        }
    }

    boolean isLast(Page page) {
        return predecessorSucessorMap.get(page) == null;
    }

    public int size() {
        return idPageMap.size();
    }
}
